require "rails_enhancer/engine"
require 'rails_enhancer/controller/base'

module RailsEnhancer
  module ControllerEnhancer
    def initialize
      build_actions
      super
    end

    private

    def split_class_name
      self.class.to_s.split("::")
    end

    def build_actions
      splited_class_name = split_class_name
      cl_name = splited_class_name.pop
      available_class_files(splited_class_name, cl_name).each do |name|
        self.class.redefine_method(name) do
          Object.const_get( splited_class_name.join('::') + "::" + cl_name + 'Actions' + '::' + name.classify).new(self).call
        end
      end
    end

    def available_class_files(splited_class_name, cl_name)
      underscored_path = splited_class_name.map{|e| e.underscore}
      Dir[Rails.root.join('app','controllers',*underscored_path, "#{cl_name.underscore}_actions", '*.rb').to_s].map{|e| e.split('/').last.gsub('.rb','')}
    end
  end
end